package com.example.texted.decoratorpattern;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;

public class DecorateAnimal implements Animal {

    private Animal animal;
    private Class<? extends Feature> clz;

    public DecorateAnimal(Animal animal, Class<? extends Feature> clz) {
        this.animal = animal;
        this.clz = clz;
    }

    @Override
    public void doStuff() {
        //具体包装行为
        InvocationHandler handler = (proxy, method, args) -> {
            Object obj = null;
            //设置包装器条件
            if (Modifier.isPublic(method.getModifiers())) {
                obj = method.invoke(clz.newInstance(), args);
            }
            animal.doStuff();
            return obj;
        };
        //当前加载器
        ClassLoader cl = getClass().getClassLoader();
        //动态代理 由Handler决定如何包装
        Feature proxy = (Feature) Proxy.newProxyInstance(cl, clz.getInterfaces(), handler);
        proxy.load();
    }
}
